/****************************************
 * 文件名：   tel.c
 * 作者：     fengjunhui
 * 修改时间： 3018-1-2
 * 文件说明： 串口应用编程之拨打电话
 ****************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <termios.h>
#include "uart_api.h"

int gprs_fd;
char *tel_num="18883765905";

void call_tel(char *tel)
{
	printf("enter call_tel .....\n");
	int n=0,ret=0,num=0;
	char end=26;
	char buff[128]={0};

	memset(buff,0,128);//测试串口是否正常工作，尽可能的多判断返回值
	strcpy(buff,"AT\n");
	write (gprs_fd,buff,strlen(buff));
	read(gprs_fd,buff,128);		
	if(strncmp(buff,"OK",2)){
		printf("serial port connected success \n");	
	}else{
		printf("serial port connected failed  \n");
	}	
	sleep(1);		

	printf("tel ......\n");
	memset(buff,0,128);
	sprintf(buff,"ATD%s;",tel_num);  //打电话
	strcat(buff,"\n");
	printf("buff :%s.\n",buff);
	write (gprs_fd,buff,strlen(buff));
	read(gprs_fd,buff,128);
	printf("read from gprs 拨打:%s\n",buff);
	
	sleep(15); //15s之后挂断
	printf("挂断.....");
	memset(buff,0,128);//挂断电话
	strcpy(buff,"ATH;");
	strcat(buff,"\n");
	write (gprs_fd,buff,strlen(buff));
	read(gprs_fd,buff,128);
	printf("read from gprs 挂断:%s\n",buff);
	//如果下面的代码加上while就算不停的重拨，这叫灌水,这样的事不要去做
	sleep(15);
	printf("重拨....\n");
	memset(buff,0,128);//测试串口是否正常工作，尽可能的多判断返回值
	strcpy(buff,"ATDL;");
	strcat(buff,"\n");
	write (gprs_fd,buff,strlen(buff));
	read(gprs_fd,buff,128);
	printf("read from gprs 重拨:%s\n",buff);
	sleep(10);
	return ;
}


int main()
{
	char buff[128]={0};
	if ((gprs_fd = open_port("/dev/ttyUSB1")) < 0){
		perror("open_port");
		return 1;
	}
	printf("gprs_fd :%d.\n",gprs_fd);
	
	if (set_com_config(gprs_fd, 9600, 8, 'N', 1) < 0){
		perror("set_com_config");
		return 1;
	}

	sleep(1);
	call_tel(tel_num);

	close(gprs_fd);
	
	return 0;
}
